let express = require('express');
let router = express.Router();
const mysql = require('mysql')
const {execute} = require('../utils/mysql')

const {token} = require("../utils/token")


/* GET home page. */
class Response {
    constructor(code, msg, data) {
        this.code = code
        this.msg = msg
        this.data = data
    }
}

// 查询所有用户表
router.get('/', function (req, res, next) {
    execute("select * from userinfo").then(result => {
        let response = new Response(200, "查询成功", result)
        res.status(200).send(response)
    })
});
//登录接口
router.post('/login', (req, res) => {
    // const {authorization} = req.headers
    // console.log('authorization', authorization)
    // const da = token.decrypt(authorization)
    // console.log("----token", da)
    const data = req.body
    let {username, password} = data
    let getInfoByNameSQL = `select *
                            from userinfo
                            where username = "${username}"`
    execute(getInfoByNameSQL).then(result => {
        if (result.length > 0) {
            if (result[0].password === password) {
                // 生成token 并返回
                let Token = token.encrypt({username}, '1d')
                result[0].Token = Token
                let response = new Response(200, "登录成功", result)
                // console.log(result)
                res.status(200).send(response)
            }


        } else {
            let response = new Response(404, "用户不存在", result)
            res.status(404).send(response)
        }
    })

    // res.status(200).send(req)
})
//注册接口
router.post('/register', (req, res) => {
    const body = req.body
    let {username, password} = body
    let registerSQL = `select * from userinfo where username = '${username}'`
    execute(registerSQL).then(result => {
        const len = result.length
        if (result.length === 0) {
            // console.log({result})
            let addUserSQL = `insert into userinfo(username,password) values('${username}','${password}') `
            execute(addUserSQL).then(result => {
                execute(`select * from userinfo where username = '${username}'`).then(result => {
                    let response = new Response(201, '创建成功', result)
                    res.status(201).send(response)

                })
            })
        } else {
            let response = new Response(409, "用户已存在", result)
            res.status(409).send(response)
        }
    })
})

module.exports = router;
